<template>
  <WeEditor
    ref="editorDom"
    class="editor"
    :toolbar-option="toolbar"
    :editable-option="editable"
    :html.sync="inputHtml"
    :style="{ 'z-index': zIndex }"
  />
</template>

<script>
import { WeEditor, useWangEditor } from "wangeditor5-for-vue2";
import "@wangeditor/editor/dist/css/style.css";
import { systemUploadFile } from "@/api/file";
export default {
  name: "WangEditor",
  components: {
    WeEditor,
  },
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    // 是否只读
    disabled: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "",
    },
    zIndex: {
      type: Number,
      default: 10001,
    },
  },
  data() {
    const { editable, toolbar, syncContent, clearContent } = useWangEditor({
      placeholder: this.placeholder || "请输入",
      config: {
        delay: 2000,
        readOnly: false,
        MENU_CONF: {
          uploadImage: {
            customUpload(file, insertFn) {
              systemUploadFile({ file }).then((data) => {
                data.forEach((item) => {
                  insertFn(item.attUrl, item.originalName, item.attUrl);
                });
              });
            },
          },
          uploadVideo: {
            customUpload(file, insertFn) {
              systemUploadFile({ file }).then((data) => {
                data.forEach((item) => {
                  insertFn(item.attUrl);
                });
              });
            },
          },
        },
      },
    });
    return {
      editable,
      toolbar,
      syncContent,
      clearContent,
    };
  },
  computed: {
    // 富文本框html
    inputHtml: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("change", val);
      },
    },
  },
  updated() {
    if (this.disabled && this.editable?.config) {
      this.editable.config.readOnly = true;
    }
  },
  destroyed() {
    this.clearContent();
  },
};
</script>

<style lang="scss" scoped>
.editor {
  border: 1px solid #d9d9d9;
  border-radius: 2px;

  :deep([id|="w-e-textarea"]) {
    min-height: 400px;
  }
}
</style>
